package com.langyiquan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.langyiquan.bo.OrderItemsCommentBO;
import com.langyiquan.bo.ShopcartBO;
import com.langyiquan.bo.SubmitOrderBO;
import com.langyiquan.config.DeliverResource;
import com.langyiquan.enums.OrderStatus;
import com.langyiquan.enums.YesOrNo;
import com.langyiquan.exception.http.OrderException;
import com.langyiquan.exception.http.ParamException;
import com.langyiquan.mapper.*;
import com.langyiquan.mapper.custom.ItemCommentCustomMapper;
import com.langyiquan.mapper.custom.OrdersCustomMapper;
import com.langyiquan.pojo.*;
import com.langyiquan.service.AddressService;
import com.langyiquan.service.ItemService;
import com.langyiquan.service.LockService;
import com.langyiquan.service.OrderService;
import com.langyiquan.utils.DateUtil;
import com.langyiquan.utils.HttpUtils;
import com.langyiquan.utils.PagedGridResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.langyiquan.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.n3r.idworker.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private Sid sid;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AddressService addressService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private OrdersCustomMapper ordersCustomMapper;

    @Autowired
    private OrderItemsMapper orderItemsMapper;

    @Autowired
    private ItemCommentCustomMapper itemCommentCustomMapper;

    @Autowired
    private DeliverResource deliverResource;

    @Autowired
    private LockService lockService;

    final static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public OrderVO createOrder(SubmitOrderBO submitOrderBO,String userId) {

        String addressId = submitOrderBO.getAddressId();
        String itemSpecIds = submitOrderBO.getItemSpecIds();
        Integer payMethod = submitOrderBO.getPayMethod();
        String leftMsg = submitOrderBO.getLeftMsg();

        // 包邮费用设置为0
        Integer postAmount = 0;

        String orderId = sid.nextShort();
        System.out.println("userId"+userId);
        UserAddress address = addressService.queryUserAddress(userId, addressId);

        if(StringUtils.isBlank(address.getId())){
            throw new ParamException(3002);
        }

        String lock_key = UUID.randomUUID().toString();
        OrderVO orderVO = new OrderVO();
        lockService.lock(lock_key);
        try {
            // 1. 新订单数据保存
            Orders newOrder = new Orders();
            newOrder.setId(orderId);
            newOrder.setUserId(userId);

            newOrder.setReceiverName(address.getReceiver());
            newOrder.setReceiverMobile(address.getMobile());
            newOrder.setReceiverAddress(address.getProvince() + " "
                    + address.getCity() + " "
                    + address.getDistrict() + " "
                    + address.getDetail());

            newOrder.setPostAmount(postAmount);

            newOrder.setPayMethod(payMethod);
            newOrder.setUserMsg(leftMsg);

            newOrder.setIsComment(YesOrNo.NO.type);
            newOrder.setIsDelete(YesOrNo.NO.type);
            newOrder.setCreatedTime(new Date());
            newOrder.setUpdatedTime(new Date());


            // 2. 循环根据itemSpecIds保存订单商品信息表
            String itemSpecIdArr[] = itemSpecIds.split(",");
            Integer totalAmount = 0;    // 商品原价累计
            Integer realPayAmount = 0;  // 优惠后的实际支付价格累计

            String itemSpecId = itemSpecIdArr[0];

            int buyCounts = submitOrderBO.getBuyCounts();

            // 2.1 根据规格id，查询规格的具体信息，主要获取价格
            ItemSpec itemSpec = itemService.queryItemSpecById(itemSpecId);
            totalAmount += itemSpec.getPriceNormal() * buyCounts;
            realPayAmount += itemSpec.getPriceDiscount() * buyCounts;

            // 2.2 根据商品id，获得商品信息以及商品图片
            String itemId = itemSpec.getItemId();
            ItemBaseInfoVO item = itemService.queryItemById(itemId);
            String imgUrl = itemService.queryItemMainImgById(itemId);

            // 2.3 循环保存子订单数据到数据库
            String subOrderId = sid.nextShort();
            OrderItems subOrderItem = new OrderItems();
            subOrderItem.setId(subOrderId);
            subOrderItem.setOrderId(orderId);
            subOrderItem.setItemId(itemId);
            subOrderItem.setItemName(item.getItemName());
            subOrderItem.setItemImg(imgUrl);
            subOrderItem.setBuyCounts(buyCounts);
            subOrderItem.setItemSpecId(itemSpecId);
            subOrderItem.setItemSpecKey(itemSpec.getSpecKey());
            subOrderItem.setItemSpecName(itemSpec.getSpecName());
            subOrderItem.setPrice(itemSpec.getPriceDiscount());
            orderItemsMapper.insert(subOrderItem);

            // 2.4 在用户提交订单以后，规格表中需要扣除库存
            itemService.decreaseItemSpecStock(itemSpecId, buyCounts);

            newOrder.setTotalAmount(totalAmount);
            newOrder.setRealAmount(realPayAmount);
            newOrder.setPayAmount(realPayAmount+postAmount);
            newOrder.setOrderStatus(OrderStatus.WAIT_PAY.type);
            newOrder.setCreatedTime(new Date());
            ordersMapper.insert(newOrder);

            // 3. 构建自定义订单vo
            orderVO.setOrderId(orderId);
            return orderVO;
        }catch (Exception e) {
            logger.error("message:"+e.getMessage());
            throw new OrderException(6005);
        }finally {
            lockService.unlock(lock_key);
        }

    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public OrderVO createOrder(SubmitOrderBO submitOrderBO, List<ShopcartBO> shopcartList,String userId) {

        String addressId = submitOrderBO.getAddressId();
        String itemSpecIds = submitOrderBO.getItemSpecIds();
        Integer payMethod = submitOrderBO.getPayMethod();
        String leftMsg = submitOrderBO.getLeftMsg();

        // 包邮费用设置为0
        Integer postAmount = 0;

        String orderId = sid.nextShort();

        UserAddress address = addressService.queryUserAddress(userId, addressId);

        if(StringUtils.isBlank(address.getId())){
            throw new ParamException(3002);
        }

        String lock_key = UUID.randomUUID().toString();
        OrderVO orderVO = new OrderVO();
        lockService.lock(lock_key);
        try {
            // 1. 新订单数据保存
            Orders newOrder = new Orders();
            newOrder.setId(orderId);
            newOrder.setUserId(userId);

            newOrder.setReceiverName(address.getReceiver());
            newOrder.setReceiverMobile(address.getMobile());
            newOrder.setReceiverAddress(address.getProvince() + " "
                    + address.getCity() + " "
                    + address.getDistrict() + " "
                    + address.getDetail());

            newOrder.setPostAmount(postAmount);

            newOrder.setPayMethod(payMethod);
            newOrder.setUserMsg(leftMsg);

            newOrder.setIsComment(YesOrNo.NO.type);
            newOrder.setIsDelete(YesOrNo.NO.type);
            newOrder.setCreatedTime(new Date());
            newOrder.setUpdatedTime(new Date());


            // 2. 循环根据itemSpecIds保存订单商品信息表
            String itemSpecIdArr[] = itemSpecIds.split(",");
            Integer totalAmount = 0;    // 商品原价累计
            Integer realPayAmount = 0;  // 优惠后的实际支付价格累计

            List<ShopcartBO> toBeRemovedShopCartList = new ArrayList<>();
            for (String itemSpecId : itemSpecIdArr) {
                ShopcartBO cartItem = null;
                for(ShopcartBO sc: shopcartList){
                    String temSpecId = sc.getSpecId();
                    if(temSpecId.equals(itemSpecId)){
                        cartItem = sc;
                    }
                }

                int buyCounts = cartItem.getBuyCounts();
                toBeRemovedShopCartList.add(cartItem);

                // 2.1 根据规格id，查询规格的具体信息，主要获取价格
                ItemSpec itemSpec = itemService.queryItemSpecById(itemSpecId);
                totalAmount += itemSpec.getPriceNormal() * buyCounts;
                realPayAmount += itemSpec.getPriceDiscount() * buyCounts;

                // 2.2 根据商品id，获得商品信息以及商品图片
                String itemId = itemSpec.getItemId();
                ItemBaseInfoVO item = itemService.queryItemById(itemId);
                String imgUrl = itemService.queryItemMainImgById(itemId);

                // 2.3 循环保存子订单数据到数据库
                String subOrderId = sid.nextShort();
                OrderItems subOrderItem = new OrderItems();
                subOrderItem.setId(subOrderId);
                subOrderItem.setOrderId(orderId);
                subOrderItem.setItemId(itemId);
                subOrderItem.setItemName(item.getItemName());
                subOrderItem.setItemImg(imgUrl);
                subOrderItem.setBuyCounts(buyCounts);
                subOrderItem.setItemSpecId(itemSpecId);
                subOrderItem.setItemSpecKey(itemSpec.getSpecKey());
                subOrderItem.setItemSpecName(itemSpec.getSpecName());
                subOrderItem.setPrice(itemSpec.getPriceDiscount());
                orderItemsMapper.insert(subOrderItem);

                // 2.4 在用户提交订单以后，规格表中需要扣除库存
                itemService.decreaseItemSpecStock(itemSpecId, buyCounts);
            }

            newOrder.setTotalAmount(totalAmount);
            newOrder.setRealAmount(realPayAmount);
            newOrder.setPayAmount(realPayAmount+postAmount);
            newOrder.setOrderStatus(OrderStatus.WAIT_PAY.type);
            newOrder.setCreatedTime(new Date());
            ordersMapper.insert(newOrder);

            // 3. 构建自定义订单vo
            orderVO.setOrderId(orderId);
            orderVO.setToBeRemovedShopCartList(toBeRemovedShopCartList);
            return orderVO;
        } catch (Exception e) {
            logger.error("message:"+e.getMessage());
            throw new OrderException(6005);
        } finally {
            lockService.unlock(lock_key);
        }

    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateOrderStatus(String orderId, Integer orderStatus) {

        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setOrderStatus(orderStatus);
        if(orderStatus == OrderStatus.WAIT_RECEIVE.type){
            orders.setDeliverTime(new Date());
        }else if(orderStatus == OrderStatus.WAIT_DELIVER.type){
            orders.setPayTime(new Date());
        }else if(orderStatus == OrderStatus.SUCCESS.type){
            orders.setSuccessTime(new Date());
        }else if(orderStatus == OrderStatus.CLOSE.type){
            orders.setCloseTime(new Date());
        }

        ordersMapper.updateByPrimaryKeySelective(orders);
    }

    @Override
    public void updateOrderReceive(String orderId, String deliverCode) {

        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setDeliverTime(new Date());
        orders.setDeliverCode(deliverCode);
        ordersMapper.updateByPrimaryKeySelective(orders);

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void closeOrder()  {

        Orders orders = new Orders();
        orders.setOrderStatus(OrderStatus.WAIT_PAY.type);
        List<Orders> list = ordersMapper.select(orders);
        for(Orders os : list){
            Date createTime = os.getCreatedTime();
            int seconds = 0;
            try {
                seconds = DateUtil.longOfTwoDate(createTime,new Date());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(seconds >= 1000*15){
                Orders closeOrder = new Orders();
                closeOrder.setId(os.getId());
                closeOrder.setOrderStatus(OrderStatus.CLOSE.type);
                closeOrder.setCloseTime(new Date());
                ordersMapper.updateByPrimaryKeySelective(closeOrder);
            }
        }

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult queryMyOrders(String userId, Integer orderStatus, Integer page, Integer pageSize) {

        Map<String,Object> map= new HashMap<String,Object>();
        map.put("userId",userId);
        if(orderStatus != null){
            map.put("orderStatus",orderStatus);
        }

        PageHelper.startPage(page,pageSize);
        List<MyOrdersVO> list = ordersCustomMapper.queryMyOrders(map);

        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());

        return grid;

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<OrderItems> queryPendingComment(String orderId) {
        OrderItems items = new OrderItems();
        items.setOrderId(orderId);
        return orderItemsMapper.select(items);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveComment(String orderId, String userId, List<OrderItemsCommentBO> commentList) {

        // 1. 保存评价 items_comments
        for (OrderItemsCommentBO oic : commentList) {
            oic.setCommentId(sid.nextShort());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("commentList", commentList);
        itemCommentCustomMapper.saveComments(map);

        // 2. 修改订单表改已评价 orders
        Orders order = new Orders();
        order.setId(orderId);
        order.setIsComment(YesOrNo.YES.type);
        ordersMapper.updateByPrimaryKeySelective(order);

        // 3. 修改订单状态表的留言时间 order_status
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setCommentTime(new Date());
        ordersMapper.updateByPrimaryKeySelective(orders);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult getMyComment(String userId,Integer page,Integer pageSize) {

        Map<String,Object> map= new HashMap<>();
        map.put("userId",userId);

        PageHelper.startPage(page,pageSize);
        List<MyCommentVO> list = itemCommentCustomMapper.queryMyComments(map);

        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());

        return grid;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Orders queryOrder(String orderId, String userId) {
        Orders orders = ordersMapper.selectByPrimaryKey(orderId);
        if(orders.getUserId().equals(userId)){
            return orders;
        }
        return null;
    }

    @Override
    public MyOrdersVO queryOrderInfo(String orderId, String userId) {

        Map<String,Object> map= new HashMap<String,Object>();
        map.put("userId",userId);
        map.put("orderId",orderId);

        MyOrdersVO myOrders = ordersCustomMapper.queryOrderInfo(map);
        return myOrders;

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteOrder(String orderId) {
        Orders orders = new Orders();
        orders.setIsDelete(YesOrNo.YES.type);
        orders.setId(orderId);
        ordersMapper.updateByPrimaryKeySelective(orders);
    }

    @Transactional(propagation=Propagation.SUPPORTS)
    @Override
    public OrderStatusCountsVO getOrderStatusCounts(String userId) {

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);

        map.put("orderStatus", OrderStatus.WAIT_PAY.type);
        int waitPayCounts = ordersCustomMapper.getMyOrderStatusCounts(map);

        map.put("orderStatus", OrderStatus.WAIT_DELIVER.type);
        int waitDeliverCounts = ordersCustomMapper.getMyOrderStatusCounts(map);

        map.put("orderStatus", OrderStatus.WAIT_RECEIVE.type);
        int waitReceiveCounts = ordersCustomMapper.getMyOrderStatusCounts(map);

        map.put("orderStatus", OrderStatus.SUCCESS.type);
        map.put("isComment", YesOrNo.NO.type);
        int waitCommentCounts = ordersCustomMapper.getMyOrderStatusCounts(map);

        OrderStatusCountsVO countsVO = new OrderStatusCountsVO(waitPayCounts,
                waitDeliverCounts,
                waitReceiveCounts,
                waitCommentCounts);
        return countsVO;
    }

    @Transactional(propagation=Propagation.SUPPORTS)
    @Override
    public JSONObject getDeliverStatus(String orderId) {

        Orders orders = ordersMapper.selectByPrimaryKey(orderId);

        String host = deliverResource.getHost();
        String path = deliverResource.getPath();
        String method = deliverResource.getMethod();
        String appcode = deliverResource.getAppcode();

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("com", "auto");
        querys.put("nu", "4303866666164");
        querys.put("receiverPhone","7377");
        //querys.put("nu", orders.getDeliverCode());

        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            HttpEntity httpEntity = response.getEntity();
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(httpEntity));
            return jsonObject;
        } catch (Exception e) {
            throw new OrderException(6009);
        }
    }
}
